/**********************************
 * @Author: Your Name
 * @LastEditor: Your Name
 * @LastEditTime: 2025-11-07
 * Copyright © 2025 Your Name
 **********************************/

import { apiManagementMockData } from './mock'

// 模拟API延迟
const delay = ms => new Promise(resolve => setTimeout(resolve, ms))

// 模拟分页处理
function handlePagination(data, params) {
  const page = params.page || 1
  const pageSize = params.pageSize || 10
  const start = (page - 1) * pageSize
  const end = start + pageSize
  return {
    list: data.slice(start, end),
    total: data.length,
    page,
    pageSize,
  }
}

// 模拟搜索过滤
function handleSearch(data, params) {
  let result = [...data]

  // 根据API密钥名称过滤
  if (params.name) {
    result = result.filter(item => item.name.toLowerCase().includes(params.name.toLowerCase()))
  }

  // 根据API密钥ID过滤
  if (params.apiKey) {
    result = result.filter(item => item.apiKey.includes(params.apiKey))
  }

  // 根据状态过滤
  if (params.status !== undefined && params.status !== null) {
    result = result.filter(item => item.status === params.status)
  }

  return result
}

// 开放API管理相关API (Mock版本)
export default {
  // 获取API密钥列表
  read: async (params = {}) => {
    await delay(500) // 模拟网络延迟

    // 获取所有API密钥数据
    let apiKeys = [...apiManagementMockData.apiKeys]

    // 应用搜索过滤
    apiKeys = handleSearch(apiKeys, params)

    // 应用分页
    const pagination = handlePagination(apiKeys, params)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: {
        list: pagination.list,
        total: pagination.total,
        page: pagination.page,
        pageSize: pagination.pageSize,
      },
    })
  },

  // 创建API密钥
  create: async (data) => {
    await delay(500) // 模拟网络延迟

    // 生成新的API密钥ID
    const newId = Math.max(...apiManagementMockData.apiKeys.map(k => k.id), 0) + 1

    // 生成API密钥和密文（模拟）
    const apiKey = `api_key_${Math.random().toString(36).substr(2, 12)}`
    const secretKey = `secret_key_${Math.random().toString(36).substr(2, 16)}`

    // 创建新API密钥对象
    const newApiKey = {
      id: newId,
      name: data.name,
      description: data.description,
      apiKey,
      secretKey,
      status: data.status !== undefined ? data.status : 'ENABLED',
      expireTime: data.expireTime,
      permissions: data.permissions || [],
      ipWhitelist: data.ipWhitelist || [],
      ipBlacklist: data.ipBlacklist || [],
      rateLimitConfig: data.rateLimitConfig || {
        requestsPerSecond: 100,
        requestsPerMinute: 1000,
        requestsPerHour: 10000,
      },
      ownerId: data.ownerId || 1,
      createdBy: data.createdBy || 1,
      updatedBy: data.updatedBy || 1,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }

    // 添加到API密钥列表
    apiManagementMockData.apiKeys.push(newApiKey)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: newApiKey,
    })
  },

  // 更新API密钥
  update: async (data) => {
    await delay(500) // 模拟网络延迟

    // 查找并更新API密钥
    const index = apiManagementMockData.apiKeys.findIndex(k => k.id === data.id)
    if (index === -1) {
      return Promise.reject({
        code: 404,
        message: 'API密钥不存在',
      })
    }

    // 更新API密钥数据
    apiManagementMockData.apiKeys[index] = {
      ...apiManagementMockData.apiKeys[index],
      ...data,
      updatedAt: new Date().toISOString(),
    }

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: apiManagementMockData.apiKeys[index],
    })
  },

  // 删除API密钥
  delete: async (id) => {
    await delay(500) // 模拟网络延迟

    // 查找并删除API密钥
    const index = apiManagementMockData.apiKeys.findIndex(k => k.id === id)
    if (index === -1) {
      return Promise.reject({
        code: 404,
        message: 'API密钥不存在',
      })
    }

    apiManagementMockData.apiKeys.splice(index, 1)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: null,
    })
  },

  // 生成新的API密钥
  regenerateApiKey: async (id) => {
    await delay(500) // 模拟网络延迟

    // 查找API密钥
    const index = apiManagementMockData.apiKeys.findIndex(k => k.id === id)
    if (index === -1) {
      return Promise.reject({
        code: 404,
        message: 'API密钥不存在',
      })
    }

    // 生成新的API密钥
    const newApiKey = `api_key_${Math.random().toString(36).substr(2, 12)}`

    // 更新API密钥
    apiManagementMockData.apiKeys[index].apiKey = newApiKey
    apiManagementMockData.apiKeys[index].updatedAt = new Date().toISOString()

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: apiManagementMockData.apiKeys[index],
    })
  },

  // 获取API使用统计
  getUsageStats: async (params = {}) => {
    await delay(500) // 模拟网络延迟

    // 获取所有统计数据
    let stats = [...apiManagementMockData.apiUsageStats]

    // 应用过滤条件
    if (params.apiKey) {
      stats = stats.filter(s => s.apiKeyId === params.apiKey)
    }

    // 按时间范围过滤
    if (params.startDate) {
      stats = stats.filter(s => new Date(s.date) >= new Date(params.startDate))
    }

    if (params.endDate) {
      stats = stats.filter(s => new Date(s.date) <= new Date(params.endDate))
    }

    // 按时间粒度聚合
    if (params.granularity === 'daily') {
      // 按天聚合
      const aggregatedStats = {}
      stats.forEach((stat) => {
        const date = stat.date.split('T')[0] // 只取日期部分
        if (!aggregatedStats[date]) {
          aggregatedStats[date] = {
            date,
            totalRequests: 0,
            successfulRequests: 0,
            failedRequests: 0,
            avgResponseTime: 0,
            totalTraffic: 0,
          }
        }

        aggregatedStats[date].totalRequests += stat.totalRequests
        aggregatedStats[date].successfulRequests += stat.successfulRequests
        aggregatedStats[date].failedRequests += stat.failedRequests
        aggregatedStats[date].totalTraffic += stat.totalTraffic
        // 简单平均响应时间
        aggregatedStats[date].avgResponseTime
          = (aggregatedStats[date].avgResponseTime + stat.avgResponseTime) / 2
      })

      stats = Object.values(aggregatedStats)
    }

    // 应用分页
    const pagination = handlePagination(stats, params)

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: {
        list: pagination.list,
        total: pagination.total,
        page: pagination.page,
        pageSize: pagination.pageSize,
      },
    })
  },

  // 获取API访问控制选项
  getAccessControlOptions: async () => {
    await delay(300) // 模拟网络延迟

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: apiManagementMockData.accessControlOptions,
    })
  },

  // 获取权限选项
  getPermissionOptions: async () => {
    await delay(300) // 模拟网络延迟

    return Promise.resolve({
      code: 0,
      message: 'success',
      data: apiManagementMockData.permissionOptions,
    })
  },
}
